library(ggplot2)
library(dplyr)
library(modelsummary)
library(kableExtra)
library(stringr)
library(fixest)
library(stargazer)
library(gridExtra)
library(flextable)

survey_long <- readRDS("data/df_long.rds")

survey_long <- survey_long %>% filter(d_affiliated == 1 & d_ownparty == 0)
survey_long <- survey_long %>% 
  group_by(meta_UUID) %>%
  mutate(N_ind = n(), 
         weights = meta_Weight / N_ind,
         weights_manual = manual_weights2 / N_ind) 

votes <- read.csv("data/cmp_votes.csv") %>% 
  select(evaluated_party, pervote)

survey_long <- survey_long %>% left_join(votes) %>% 
  group_by(meta_UUID) %>% 
  mutate(sum_votes = sum(pervote), 
         perc_vote = pervote / sum_votes, 
         weights_party = meta_Weight * perc_vote)

########### Regression analyses

m1 <- feols(close_num ~ feeling_toward, survey_long,
            cluster = "dem_country_code", weights = survey_long$weights_party)
m2 <- feols(close_num ~ feeling_toward | dem_country_code, survey_long,
            weights = survey_long$weights_party)
m3 <- feols(close_num ~ feeling_toward | meta_UUID, survey_long %>% filter(dem_country_code != "US"), 
            weights = survey_long$weights_party[survey_long$dem_country_code != "US"])

options("modelsummary_format_numeric_latex" = "plain")
models <- list("(1)" = m1, "(2)" = m2, "(3)" = m3)

tab <- modelsummary(models, output = 'tables/TableA8.html', stars = TRUE,
                    coef_rename = c("feeling_toward" = "Feeling", 
                                    "dem_country_code" = "Country-FE", 
                                    "meta_UUID" = "Individual-FE"),
                    coef_omit = c("(Intercept)"),
                    gof_omit = "AIC|BIC|Log|Pseudo|Adj|Within|Std.Errors",
                    statistic = "p.value")

